package cn.neusoft.interceptor;

import cn.neusoft.vo.ResultBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 管理员前端的拦截器
 * 登录成功就进行放行
 */
public class LoginInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//拦截器先进行获取session
		HttpSession session= request.getSession();
		//一般在这里进行写拦截器的时候，在前端还要进行响应拦截器，但是在springmvc中还要进行配置拦截器
		Object adminUser=session.getAttribute("adminUser");
		System.out.println(adminUser);
		if(adminUser==null) {
			//说明未登录或者是用户名错误，如果新来的用户，先自动分配一个session
			ObjectMapper objectMapper=new ObjectMapper();
			String json=objectMapper.writeValueAsString(ResultBean.ERROR(50001,"未登录"));

			//设置返回的内容
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(json);
			return false;
		}
		return true;
	}
}
